package account

import (
    "fmt"
    "strconv"

    "github.com/gin-gonic/gin"
    "iip/account/account_type"
    "iip/lib"
)


func (s *Account) CasbinCreate(c *gin.Context) {
    type Policy struct {
        Role   string `json:"role"`
        URL    string `json:"url"`
        Action string `json:"methord"`
    }

    req := &struct {
        PolicyList []*Policy `json:"policy_list"`
    }{}
    if err := c.ShouldBindJSON(req); err != nil {
        s.logger.Error(err.Error())
        lib.JsonError(c, err.Error())
        return
    }
    s.logger.Info("创建规则", req)

    for _, p := range req.PolicyList {
        ok, err := s.csb.AddPolicy(p.Role, p.URL, p.Action)
        if err != nil {
            s.logger.Error(err.Error())
            lib.JsonError(c, err.Error())
            return
        }
        if !ok {
            err := fmt.Errorf("cannot create policy %s %s %s", p.Role, p.URL, p.Action)
            s.logger.Error(err.Error())
            lib.JsonError(c, err.Error())
            return
        }
    }
    if err := s.csb.SavePolicy(); err != nil {
        s.logger.Error(err.Error())
        lib.JsonError(c, err.Error())
        return
    }
    lib.JsonOK(c)
}


func (s *Account) CasbinGet(c *gin.Context) {








































}


func (s *Account) CasbinUpdate() error {

    role_list, err := s.GetAllRole()
    if err != nil {
        return err
    }

    s.csb.ClearPolicy()

    for _, role := range role_list {

        res_list, err := s.GetRoleResources(role.ID)
        if err != nil {
            return err
        }


        for _, res := range res_list {
            if res.Type != account_type.ResourceTypeAPI {
                continue
            }

            sub := strconv.FormatInt(role.ID, 10)
            obj := res.URL
            act := res.Method

            ok, err := s.csb.AddPolicy(sub, obj, act)
            if err != nil {
                s.logger.Error(err.Error())
                return err
            }
            if !ok {
                err := fmt.Errorf("cannot create policy %s %s %s", sub, obj, act)
                s.logger.Error(err.Error())
                return err
            } else {
                s.logger.Infof("设置权限规则 %s %s %s", sub, obj, act)
            }
        }
    }

    plist := s.csb.GetPolicy()
    for _, p := range plist {
        s.logger.Info(p)
    }

    return nil
}
